// worker执行队列
export default class WorkerQueue {
  constructor() {
    this.workerArr = []
    this.run = false
    const hardwareConcurrency = window.navigator.hardwareConcurrency || 4
    this.limit = hardwareConcurrency - 1
    this.workingNum = 0
  }

  addWorker(fn, context, args) {
    this.workerArr.push([fn, context, args])
    if (this.run && this.workingNum < this.limit) {
      this.execute(this.workerArr.shift())
    }
  }

  unshiftWorker(fn, context, args) {
    this.workerArr.unshift([fn, context, args])
    if (this.run && this.workingNum < this.limit) {
      this.execute(this.workerArr.shift())
    }
  }

  execute(args) {
    args[0].call(args[1], args[2])
    this.workingNum += 1

    if (this.workerArr.length > 0 && this.workingNum < this.limit) {
      this.execute(this.workerArr.shift())
    }
  }

  changeStatus() {
    this.run = true
    if (this.workerArr.length > 0 && this.workingNum < this.limit) {
      this.execute(this.workerArr.shift())
    }
  }
}
